package com.zhoux.mongo.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.XMLOutputter;

public class XmlUtil {
	private static Log log=LogFactory.getLog(XmlUtil.class);
	private static SAXBuilder builder=new SAXBuilder();
	/**
	 * 檢查表是否在庫種存在
	 * @param dataBaseName
	 * @param tableName
	 * @return true 表存在 false不存在
	 */
	public static Boolean decideTable(String dataBaseName,String tableName){
		Boolean isExists=false;
		try {
			Element root =getRoot(dataBaseName);
			 List<Element> tablelist=root.getChildren();
			 for (Element element : tablelist) {
				if(tableName.equals(element.getAttributeValue("name"))){
					isExists=true;
				};
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return isExists;
	}
	public static boolean newTable(String dataBaseName,String tableName) {
		try {
			dataBaseName=StringUtil.formatFileName(dataBaseName);
			Document doc=builder.build(dataBaseName);
			Element root =doc.getRootElement();
			Element table=new Element("table");
			table.setAttribute("name", tableName);
			root.addContent(table);
			XMLOutputter out=new XMLOutputter();
			out.output(doc, new FileOutputStream(dataBaseName));
			return true;
		} catch (Exception e) {
			log.error("创建表失败");
			e.printStackTrace();
		}
		return false;
		
	}
	/**
	 * 删除table
	 * @param dataBaseName
	 * @param tableName
	 * @return true成功；false失败
	 */
	public static boolean dropTable(String dataBaseName,String tableName){
		try {
			dataBaseName=StringUtil.formatFileName(dataBaseName);
			Document doc=builder.build(dataBaseName);
			Element root =doc.getRootElement();
			List<Element> list = root.getChildren();
			for (Element element : list) {
				if(element.getAttributeValue("name").equals(tableName)){
					root.removeContent(element);
					XMLOutputter out=new XMLOutputter();
					out.output(doc, new FileOutputStream(dataBaseName));
					return true;
				}
			}
			return true;
		} catch (Exception e) {
			log.error("创建表失败");
			e.printStackTrace();
		}
		return false;
		
		
	}
	
	private static Element getRoot(String dataBaseName) throws JDOMException, IOException, Exception{
		Document doc=builder.build(StringUtil.formatFileName(dataBaseName));
		return doc.getRootElement();
	}
	
	public static boolean insertDocument(String dataBaseName,String tableName,String json){
		try {
			dataBaseName=StringUtil.formatFileName(dataBaseName);
			Document doc=builder.build(dataBaseName);
			Element root =doc.getRootElement();
			List<Element> list = root.getChildren();
			for (Element element : list) {
				if(element.getAttributeValue("name").equals(tableName)){
					//创建一个document
					Element newElment=new Element("document");
					newElment.addContent(json);
					newElment.setAttribute("id", StringUtil.getId());
					element.addContent(newElment);
					XMLOutputter out=new XMLOutputter();
					out.output(doc, new FileOutputStream(dataBaseName));
					return true;
				}
			}
			return true;
		} catch (Exception e) {
			log.error("创建表失败");
			e.printStackTrace();
		}
		return false;
	}
	
	public static boolean deleteDocument(String dataBaseName,String tableName,String id){
		try {
			dataBaseName=StringUtil.formatFileName(dataBaseName);
			Document doc=builder.build(dataBaseName);
			Element root =doc.getRootElement();
			List<Element> tableList = root.getChildren();
			if(tableList.size()<1){
				return true;
			}
			for (Element table : tableList) {
				if(table.getAttributeValue("name").equals(tableName)){
					List<Element> docList =table.getChildren();
					if(docList.size()<1){
						return true;
					}
					for (Element document : docList) {
						if(document.getAttributeValue("id").equals(id)){
							table.removeContent(document);
							XMLOutputter out=new XMLOutputter();
							out.output(doc, new FileOutputStream(dataBaseName));
							return true;
						}
					}
				}
			}
		} catch (Exception e) {
			log.error("删除document失败。。。");
			e.printStackTrace();
		}
		return false;
	}
	
	@SuppressWarnings("rawtypes")
	public static Map queryDocumentById(String dataBaseName,String tableName,String id){
		Map map=null;
		try {
			dataBaseName=StringUtil.formatFileName(dataBaseName);
			Document doc=builder.build(dataBaseName);
			Element root =doc.getRootElement();
			List<Element> tableList = root.getChildren();
			if(tableList.size()<1){
				log.debug("this database is empty!");
				return null;
			}
			for (Element table : tableList) {
				if(table.getAttributeValue("name").equals(tableName)){
					List<Element> docList =table.getChildren();
					if(docList.size()<1){
						log.debug("this table is empty!");
						break;
					}
					for (Element document : docList) {
						if(document.getAttributeValue("id").equals(id)){
							String str=document.getText();
							map=JsonUtil.jsonToMap(str);
							break;
						}
					}
					break;
				}
			}
		} catch (Exception e) {
			log.error("删除document失败。。。");
			e.printStackTrace();
		}
		return map;
	}
	
	public static boolean updateDocument(String dataBaseName,String tableName,Map updateMap,String id){
		boolean flag=false;
		Map map=null;
		try {
			dataBaseName=StringUtil.formatFileName(dataBaseName);
			Document doc=builder.build(dataBaseName);
			Element root =doc.getRootElement();
			List<Element> tableList = root.getChildren();
			if(tableList.size()<1){
				log.debug("this database is empty!");
			}
			for (Element table : tableList) {
				if(table.getAttributeValue("name").equals(tableName)){
					List<Element> docList =table.getChildren();
					if(docList.size()<1){
						log.debug("this table is empty!");
						break;
					}
					for (Element document : docList) {
						if(document.getAttributeValue("id").equals(id)){
							String str=document.getText();
							map=JsonUtil.jsonToMap(str);
							if(map==null){
								document.removeContent();
							}else{
								map=updateMap;
							}
							log.debug("start update document by id="+id);
							document.setText(JsonUtil.objectToString(map));
							table.setContent(document);
							root.setContent(table);
							XMLOutputter out=new XMLOutputter();
							out.output(doc, new FileOutputStream(dataBaseName));
							flag=true;
							break;
						}
					}
					break;
				}
			}
		} catch (Exception e) {
			log.error("删除document失败。。。");
			e.printStackTrace();
		}
		return flag;
	}

	public static List<HashMap> queryDpcumentList(String dataBaseName,String tableName){
		List<HashMap> list=new ArrayList<HashMap>();
		try {
			dataBaseName=StringUtil.formatFileName(dataBaseName);
			Document doc=builder.build(dataBaseName);
			Element root =doc.getRootElement();
			List<Element> tableList = root.getChildren();
			if(tableList.size()<1){
				log.debug("this database is empty!");
				return null;
			}
			for (Element table : tableList) {
				if(table.getAttributeValue("name").equals(tableName)){
					List<Element> docList =table.getChildren();
					if(docList.size()<1){
						log.debug("this table is empty!");
						break;
					}
					for (Element document : docList) {
						HashMap map=JsonUtil.jsonToMap(document.getText());
						map.put("id",document.getAttributeValue("id"));
						list.add(map);
					}
					break;
				}
			}
		} catch (Exception e) {
			log.error("查询document列表失败");
			e.printStackTrace();
		}
		return list;
	}
	
}
